/**
 * 测试脚本 - 模拟不同脚本来源发送事件数据
 * 
 * 使用方法: node test-events.js
 */

const http = require('http');

// 配置
const config = {
  host: 'localhost',
  port: process.env.SERVER_PORT || 3000,
  path: '/api/events/record',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  }
};

// 模拟的脚本来源
const scriptSources = [
  { name: 'game_client_v1', version: '1.0.0' },
  { name: 'game_client_v2', version: '2.0.0' },
  { name: 'game_mobile_app', version: '1.5.0' },
  { name: 'game_web_client', version: '0.9.0' }
];

// 模拟的事件类型
const eventTypes = [
  'game_start',
  'game_end',
  'level_complete',
  'achievement_unlocked',
  'item_purchased',
  'character_upgrade',
  'login',
  'logout'
];

// 生成随机事件数据
function generateRandomEvent() {
  const scriptSource = scriptSources[Math.floor(Math.random() * scriptSources.length)];
  const eventType = eventTypes[Math.floor(Math.random() * eventTypes.length)];
  const userId = `user_${Math.floor(Math.random() * 100) + 1}`;
  const sessionId = `session_${Math.floor(Math.random() * 1000) + 1}`;
  
  let eventData = {};
  
  // 根据事件类型生成不同的数据
  switch (eventType) {
    case 'game_start':
      eventData = { difficulty: ['简单', '中等', '困难'][Math.floor(Math.random() * 3)] };
      break;
    case 'game_end':
      eventData = { 
        score: Math.floor(Math.random() * 10000),
        duration: Math.floor(Math.random() * 3600) + 60 // 60秒到1小时
      };
      break;
    case 'level_complete':
      eventData = { 
        level: Math.floor(Math.random() * 50) + 1,
        stars: Math.floor(Math.random() * 3) + 1,
        time_taken: Math.floor(Math.random() * 300) + 30 // 30秒到5分钟
      };
      break;
    case 'achievement_unlocked':
      eventData = { 
        achievement_id: `achievement_${Math.floor(Math.random() * 20) + 1}`,
        achievement_name: `成就 ${Math.floor(Math.random() * 20) + 1}`
      };
      break;
    case 'item_purchased':
      eventData = { 
        item_id: `item_${Math.floor(Math.random() * 100) + 1}`,
        price: Math.floor(Math.random() * 1000) + 10,
        currency: ['金币', '钻石', '点券'][Math.floor(Math.random() * 3)]
      };
      break;
    default:
      eventData = { timestamp: Date.now() };
  }
  
  return {
    event_type: eventType,
    event_data: eventData,
    user_id: userId,
    session_id: sessionId,
    script_source: scriptSource.name,
    script_version: scriptSource.version
  };
}

// 发送事件数据
function sendEvent() {
  const event = generateRandomEvent();
  const data = JSON.stringify(event);
  
  config.headers['Content-Length'] = data.length;
  
  const req = http.request(config, (res) => {
    let responseData = '';
    
    res.on('data', (chunk) => {
      responseData += chunk;
    });
    
    res.on('end', () => {
      try {
        const parsedData = JSON.parse(responseData);
        console.log(`事件发送成功: ${event.script_source} - ${event.event_type} (ID: ${parsedData.event_id})`);
      } catch (e) {
        console.log(`事件发送成功: ${event.script_source} - ${event.event_type}`);
      }
    });
  });
  
  req.on('error', (error) => {
    console.error(`发送事件失败: ${error.message}`);
  });
  
  req.write(data);
  req.end();
}

// 发送多个事件
function sendMultipleEvents(count) {
  console.log(`开始发送 ${count} 个测试事件...`);
  
  let sent = 0;
  
  const intervalId = setInterval(() => {
    sendEvent();
    sent++;
    
    if (sent >= count) {
      clearInterval(intervalId);
      console.log(`已完成 ${count} 个测试事件的发送`);
    }
  }, 200); // 每200毫秒发送一个事件
}

// 默认发送20个事件
const eventCount = process.argv[2] ? parseInt(process.argv[2]) : 20;
sendMultipleEvents(eventCount);